import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from '@/store/user'
import Layout from "../layout/index.vue";

/** 路由继承类型 */
export interface extendRoute {
  hidden?: boolean;
  meta?: {
    name: string;
    // 页面主题色
    mainColor: string;
    // body 中背景图
    headerBgName: string;
  };
}

/**
 * 动态路由
 */
export const asyncRoutes = [
  {
    path: "/index",
    component: () => import("@/views/index/index.vue"),
    name: "Home",
    meta: { name: "首页", icon: "#003F8A" },
  },
  {
    path: "/shopManage",
    component: () => import("@/views/shopManage/index.vue"),
    name: "ShopManage",
    meta: { name: "库存管理", icon: "#003F8A" },
  },
  {
    path: "/orderManage",
    component: () => import("@/views/orderManage/index.vue"),
    name: "OrderManage",
    meta: { name: "订单管理", icon: "#003F8A" },
  },
  {
    path: "/procureManage",
    component: () => import("@/views/procureManage/index.vue"),
    name: "ProcureManage",
    meta: { name: "采购管理", icon: "#003F8A" },
  },
  {
    path: "/userManage",
    component: () => import("@/views/userManage/index.vue"),
    name: "userManage",
    meta: { name: "用户管理", icon: "#003F8A", auth: [1] },
  },
  {
    path: "/deptManage",
    component: () => import("@/views/deptManage/index.vue"),
    name: "deptManage",
    meta: { name: "部门管理", icon: "#003F8A", auth: [1] },
  },
  {
    path: "/baseSetting",
    component: () => import("@/views/baseSetting/index.vue"),
    name: "BaseSetting",
    meta: { name: "系统设置", icon: "#003F8A", auth: [1] },
  },
];

/**
 * 公共路由
 * @param { Boolean } keepAlive 是否需要缓存， 功能待开发
 * @param { Boolean } requireAuth 是否需要登录, 功能待开发
 */
export const constantRoutes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/",
    name: "layout",
    component: Layout,
    children: asyncRoutes,
  },
  {
    path: '/:catchAll(.*)*',
    component: () => import('@/views/errorNotFound/index.vue'),
  },
];

const router = createRouter({
  history: createWebHashHistory(), // hash
  routes: constantRoutes,
});

/** 路由拦截 */
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.getToken
  
  // 判断是否登录
  if (!token && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})


export default router;
